﻿using System.Web;
using FluentNHibernate.Cfg;
using NHibernate;
using NHibernate.Cfg;

namespace Kratos.Framework.Repositories.NHibernateProvider
{
    public class NHibernateConfiguration
    {
        private static volatile ISessionFactory _instance;

        private static volatile NHibernateConfiguration _config;

        private static readonly object Lock = new object();

        private static readonly object SycnRoot = new object();

        private NHibernateConfiguration()
        {

        }

        public static NHibernateConfiguration Config
        {
            get
            {
                if (_config == null)
                {
                    lock (SycnRoot)
                    {
                        if (_config == null)
                            _config = new NHibernateConfiguration();
                    }
                }

                return _config;
            }
        }

        public ISessionFactory SingleSessionFactory
        {
            get
            {
                if (_instance == null)
                {
                    lock (Lock)
                    {
                        if (_instance == null)
                            _instance = BuildSesscionFactory();
                    }
                }
                return _instance;
            }
        }

        private static ISessionFactory BuildSesscionFactory()
        {
            return Fluently
                    .Configure(new Configuration().Configure(HttpContext.Current.Server.MapPath("~/Config/hibernate.cfg.xml")))
                    .Mappings(m => m.FluentMappings.AddFromAssemblyOf<NHibernateConfiguration>())
                    .BuildSessionFactory();
        }
    }
}
